import { Injectable } from '@nestjs/common';
import { Request as ExpressRequest, Response as ExpressResponse } from 'express';
import axios from 'axios';
type ServiceName = 'user-service' | 'product-service' | 'order-service';
@Injectable()
export class ProxyService {
  private serviceUrls = {
    'user-service': 'http://localhost:3001',
    'product-service': 'http://localhost:3002',
    'order-service': 'http://localhost:3003'
  };

  async forwardRequest(serviceName: ServiceName, req: ExpressRequest, res: ExpressResponse) {
    try {
      const targetUrl = this.serviceUrls[serviceName];
      const path = req.originalUrl.replace(/^\/[^/]+/, ''); // 移除服务前缀
      
      const response = await axios({
        method: req.method,
        url: `${targetUrl}${path || '/'}`,
        data: req.body,
        params: req.query,
        headers: { ...req.headers, host: undefined }
      });

      res.status(response.status).json(response.data);
    } catch (error) {
      res.status(500).json({ message: 'Service unavailable' });
    }
  }
}